﻿using ConfExpert.Utility;
using DevExpress.XtraEditors.Repository;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Extensions;
using DevExpress.XtraEditors;

namespace Tailord
{
    public partial class SiparisOlustur : XPopupForm
    {

        public int OrderId { get; set; }
        public DataTable dtSiparisLines { get; set; }
        public DataTable dtUser { get; set; }
        public decimal ToplamOdeme { get; set; }

        Color ZorunluRenk;

        public SiparisOlustur(int OrderId)
        {
            InitializeComponent();
            this.OrderId = OrderId;
            Baslik.Caption = OrderId > 0 ? "Sipariş No." + OrderId : "Yeni Sipariş";
            this.Text = OrderId > 0 ? "Sipariş No." + OrderId : "Yeni Sipariş";

            gleMusteri.Properties.Assign(riCustomer);
            gleOdemeSekli.Properties.Assign(riOdemeSekli);
            gleOdemeTipi.Properties.Assign(riOdemeTipi);
            gleParaBirimi.Properties.Assign(riParaBirimi);

            gleParaBirimi.EditValue = "TL";

            ZorunluRenk = Color.PeachPuff;
        }

        private void SiparisOlustur_Load(object sender, EventArgs e)
        {
            ShowOnlyBar();
            this.WindowState = FormWindowState.Maximized;
            DataSet dsSiparis = AppSession.DataManager.ExecuteDataSet("GetRetailOrdersByOrderId", OrderId, WhoAmI);
            ds.Customer.Merge(dsSiparis.Tables[2]);

            dtSiparisLines = dsSiparis.Tables[1];
            dtUser = dsSiparis.Tables[4];
            gleUser.Properties.Assign(riUser);

            dtSiparisLines.Columns.Add("ToplamPSF", typeof(decimal), "BirimFiyat*Adet");
            dtSiparisLines.Columns.Add("IndirimTutari", typeof(decimal), "IndirimOrani*ToplamPSF/100");
            dtSiparisLines.Columns.Add("IndirimliTutar", typeof(decimal), "ToplamPSF-Isnull(IndirimTutari,0)");
            dtSiparisLines.Columns.Add("NetCiro", typeof(decimal), "IndirimliTutar/(1+KDV/100)");
            dtSiparisLines.Columns.Add("KdvTutar", typeof(decimal), "IndirimliTutar-NetCiro");
            dtSiparisLines.Columns.Add("ParaPuan", typeof(decimal), "IIF(Isnull(Puan,0) = 0, 0, NetCiro*10/100)");

            if (OrderId > 0)
            {
                DataRow drSiparis = dsSiparis.Tables[0].Rows[0];

                gleMusteri.EditValue = drSiparis["CustomerId"];
                dateSiparis.EditValue = drSiparis["SiparisTarihi"];
                gleUser.EditValue = drSiparis["UserId"];
                txtNotlar.Text = drSiparis["Notlar"].ToString();

                string ParaBirimi = " " + drSiparis["ParaBirimi"].ToString();

                ToplamOdeme = drSiparis["ToplamOdeme"].ToDecimalNN();
                decimal ToplamTutar = dtSiparisLines.Compute("Sum(IndirimliTutar)", "True").ToDecimalNN();
                decimal KalanTutar = ToplamTutar - ToplamOdeme;

                lblToplamTutar.Text = decimal.Round(ToplamTutar, 2).ToString() + ParaBirimi;
                lblOdeme.Text = decimal.Round(ToplamOdeme, 2).ToString() + ParaBirimi;
                lblKalan.Text = decimal.Round(KalanTutar, 2).ToString() + ParaBirimi;
            }
            else
            {
                dateSiparis.EditValue = DateTime.Now;
            }


            gvSiparisLines.Init(dtSiparisLines);
            
            //gleMusteri.Properties.Assign(GetCustomGLE(dsSiparis.Tables[2], "Name", "CustomerId"));
            gvSiparisLines.Columns["UrunId"].ColumnEdit = GetCustomGLE(dsSiparis.Tables[3], "Urun", "UrunId");
            gvSiparisLines.Columns["Durum"].ColumnEdit = riDurum;
            gvSiparisLines.Columns["Servis"].ColumnEdit = riServis;

            gvSiparisLines.SetCaptions("UrunId:Ürün","BirimFiyat:BirimPSF");

            gvSiparisLines.FormatAsDate("TerminTarihi");
            gvSiparisLines.FormatAsNumber(2, "NetCiro", "KdvTutar", "IndirimTutari", "IndirimliTutar", "ParaPuan");
            gvSiparisLines.AddSummary("NetCiro", "KdvTutar", "IndirimTutari", "IndirimliTutar", "ToplamPSF");

            gvSiparisLines.YanYanaGetir("Kategori:Servis");
            gvSiparisLines.YanYanaGetir("ToplamPSF:IndirimOrani");
            gvSiparisLines.YanYanaGetirCoklu("Puan","TeslimTarihi:", "IndirimTutari:", "IndirimliTutar:", "KDV:", "KdvTutar:", "NetCiro:");

            gvSiparisLines.MakeColumnInvisible("RetailOrderId", "RetailOrderKId", "KayitTarihi");
            gvSiparisLines.BestFitColumns();

            gvSiparisLines.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            gvSiparisLines.RowCellStyle += gvSiparisLines_RowCellStyle;
            gvSiparisLines.CellValueChanged += gvSiparisLines_CellValueChanged;
            gvSiparisLines.InitNewRow += gvSiparisLines_InitNewRow;
            gvSiparisLines.FocusedRowChanged += gvSiparisLines_FocusedRowChanged;
            gleOdemeTipi.EditValueChanged += gleOdemeTipi_EditValueChanged;
            gvSiparisLines.RowCellClick += gvSiparisLines_RowCellClick;

        }

        void gvSiparisLines_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Puan")
                {
                    bool currentStatus = false;
                    if (e.CellValue != DBNull.Value)
                    {
                        currentStatus = (bool)e.CellValue;
                    }
                    gvSiparisLines.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
                }
            }
        }

        void gleOdemeTipi_EditValueChanged(object sender, EventArgs e)
        {
            string OdemeTipi = gleOdemeTipi.EditValue.ToString();
            if (OdemeTipi == "Kaporadan Kalan" || OdemeTipi == "Tamamı")
            {
                decimal ToplamTutar;
                decimal.TryParse(dtSiparisLines.Compute("Sum(IndirimliTutar)", "True").ToStringNN(), out ToplamTutar);
                decimal KalanTutar = ToplamTutar - ToplamOdeme;

                txtOdenenTutar.Text = KalanTutar.ToString();
            }
            else
                txtOdenenTutar.Text = "";
        }

        void gvSiparisLines_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {            
            decimal ToplamTutar ;
            decimal.TryParse(dtSiparisLines.Compute("Sum(IndirimliTutar)", "True").ToStringNN(), out ToplamTutar);
            decimal KalanTutar = ToplamTutar - ToplamOdeme;

            lblToplamTutar.Text = decimal.Round(ToplamTutar, 2).ToString() + " TL";
            lblOdeme.Text = decimal.Round(ToplamOdeme, 2).ToString() + " TL";
            lblKalan.Text = decimal.Round(KalanTutar, 2).ToString() + " TL";

            if (cbOdeme.Checked && gleOdemeTipi.EditValue.ToString() != "Kapora")
                txtOdenenTutar.Text = KalanTutar.ToString();
        }
        
        void gvSiparisLines_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            gvSiparisLines.SetRowCellValue(e.RowHandle,"Durum", "Yeni");
        }

        void gvSiparisLines_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            gvSiparisLines.CellValueChanged -= gvSiparisLines_CellValueChanged;
            int UrunId = gvSiparisLines.GetRowCellValue(e.RowHandle, "UrunId").ToIntZero();
            string Servis = gvSiparisLines.GetRowCellValue(e.RowHandle, "Servis").ToStringNN();
            switch (e.Column.FieldName)
            {
                case "UrunId":            
                if (UrunId > 0)
                {
                    DataTable dt = ((RepositoryItemGridLookUpEdit)gvSiparisLines.Columns["UrunId"].ColumnEdit).DataSource as DataTable;
                    DataRow[] dr = dt.Select("UrunId =" + UrunId);
                    if (dr.Length > 0)
                    {
                        gvSiparisLines.SetRowCellValue(e.RowHandle, "Kategori", dr[0]["Kategori"]);
                        gvSiparisLines.SetRowCellValue(e.RowHandle, "KDV", dr[0]["KdvOrani"]);
                        if (Servis == "MTM")
                        {
                            int EklenecekGun = dr[0]["Termin"].ToIntNN();
                            DateTime dateTermin = DateTime.Now.AddDays(EklenecekGun);
                            gvSiparisLines.SetRowCellValue(e.RowHandle, "TerminTarihi", dateTermin);
                        }
                    }
                }
                else
                {
                    gvSiparisLines.SetRowCellValue(e.RowHandle, "Kategori", null);
                    gvSiparisLines.SetRowCellValue(e.RowHandle, "KDV", null);
                    gvSiparisLines.SetRowCellValue(e.RowHandle, "TerminTarihi", null);
                }
                break;

                case "Servis":
                if (UrunId > 0)
                    if (Servis == "MTM")
                    {
                        DataTable dt = ((RepositoryItemGridLookUpEdit)gvSiparisLines.Columns["UrunId"].ColumnEdit).DataSource as DataTable;
                        DataRow[] dr = dt.Select("UrunId =" + UrunId);
                        int EklenecekGun = dr[0]["Termin"].ToIntNN();
                        DateTime dateTermin = DateTime.Now.AddDays(EklenecekGun);
                        gvSiparisLines.SetRowCellValue(e.RowHandle, "TerminTarihi", dateTermin);
                    }
                    else if(Servis=="RTW")
                        gvSiparisLines.SetRowCellValue(e.RowHandle, "TerminTarihi", DateTime.Now);
                    else
                        gvSiparisLines.SetRowCellValue(e.RowHandle, "TerminTarihi", null);                    
                
                break;
                //case "BirimFiyat":
                //case "IndirimOrani":
                //DataTable dtFiyat = gvSiparisLines.Dataset().Tables[1];
                //decimal ToplamTutar = decimal.Round(dtFiyat.Compute("Sum(IndirimliTutar)", "True").ToDecimalNN(), 2);
                //lblToplamTutar.Text = ToplamTutar.ToString();
                //break;
            }
            gvSiparisLines.CellValueChanged += gvSiparisLines_CellValueChanged;
        }

        void gvSiparisLines_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "UrunId")
                {
                    int UrunId = gvSiparisLines.GetRowCellValue(e.RowHandle, "UrunId").ToIntZero();
                    if (UrunId == 0)
                        e.Appearance.BackColor = ZorunluRenk;
                }

                if (e.Column.FieldName == "Adet")
                {
                    int Adet = gvSiparisLines.GetRowCellValue(e.RowHandle, "Adet").ToIntZero();
                    if (Adet == 0)
                        e.Appearance.BackColor = ZorunluRenk;
                }

                if (e.Column.FieldName == "BirimFiyat")
                {
                    decimal BirimFiyat = gvSiparisLines.GetRowCellValue(e.RowHandle, "BirimFiyat").ToDecimalNN();
                    if (BirimFiyat == -1)
                        e.Appearance.BackColor = ZorunluRenk;
                }
            }
        }

        private void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EndGridViewEdit(gvSiparisLines);
            decimal OdenenTutar;
            Decimal.TryParse(txtOdenenTutar.Text,out OdenenTutar);

            if (gleMusteri.EditValue.ToIntZero()==0)
            {
                 XtraMessageBox.Show("Müşteri girmelisiniz!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
            }
            if (gleUser.EditValue.ToIntZero() == 0)
            {
                XtraMessageBox.Show("Siparişi alan kişiyi girmelisiniz!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (dateSiparis.EditValue.ToStringNN()== "")
            {
                XtraMessageBox.Show("Sipariş tarihi girmelisiniz!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (OdenenTutar > 0 && (gleOdemeSekli.Text == "" || gleOdemeTipi.Text == ""))
            {
                
                XtraMessageBox.Show("Tutar girmiş iseniz ödeme bilgilerini de girmelisiniz!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DataTable dtSiparis = gvSiparisLines.Dataset().Tables[1];
            DataRow[] drSiparis = dtSiparis.Select("UrunId is null or Adet is null or BirimFiyat is null");
            if (drSiparis.Length > 0)
            {
                XtraMessageBox.Show("Sipariş satırlarındaki kırmızı renkli alanları doldurmalısınız!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return; 
            }


            string SiparisXML = XML.SerializeAll(dtSiparis);
            ExecQuery("SaveRetailOrder", SiparisXML, gleMusteri.EditValue, dateSiparis.EditValue, gleOdemeTipi.EditValue, gleOdemeSekli.EditValue, gleParaBirimi.EditValue, OdenenTutar,txtNotlar.Text, gleUser.EditValue, OrderId);
            this.DialogResult = DialogResult.OK;
        }

        private void MusteriEkle_Click(object sender, EventArgs e)
        {
            using (MusteriEkle so = new MusteriEkle())
            {
                DialogResult dr = so.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    TailordDS.AppDS.CustomerRow r = ds.Customer.NewCustomerRow();
                    r.Name = so.drMusteri["Name"].ToStringNN();
                    r.CustomerId = so.drMusteri["CustomerId"].ToIntZero();
                    ds.Customer.AddCustomerRow(r);
                }
                    
            }
        }

        private void cbOdeme_CheckedChanged(object sender, EventArgs e)
        {
            gleOdemeTipi.EditValue = gleOdemeSekli.EditValue = txtOdenenTutar.Text = "";
            gleOdemeTipi.Enabled = gleOdemeSekli.Enabled = txtOdenenTutar.Enabled = cbOdeme.Checked;
        }

        private void bbiSiparisEkle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int CustomerId = gleMusteri.EditValue.ToIntZero();
            using (GomlekSiparisleri gs = new GomlekSiparisleri(CustomerId))
            {
                DialogResult dr = gs.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (CustomerId == 0)
                        gleMusteri.EditValue = gs.SelectedCustomerId;

                    DataTable dtGomlekSiparis = AppSession.DataManager.ExecuteDataTable("GetOrderKbyOrderId", gs.OrderId);
                    dtSiparisLines.Merge(dtGomlekSiparis);
                    gvSiparisLines_FocusedRowChanged(null, null);
                }
            }
        } 

        public RepositoryItemGridLookUpEdit riCustomer
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomGLE(ds.Customer, "Name", "CustomerId");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riUser
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomGLE(dtUser, "Name", "UserId");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riOdemeSekli
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomRI("OdemeSekli", false,  "Kredi Kartı", "EFT/Havale", "Nakit");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riOdemeTipi
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomRI("OdemeTipi", false, "Tamamı", "Kapora", "Kaporadan Kalan");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riParaBirimi
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomRI("Para Birimi", false, "TL", "DOLAR", "EUR");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riDurum
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomRI("Durum", false, "Yeni", "Üretim", "Bitti", "Teslim");
                return ri;
            }
        }

        public RepositoryItemGridLookUpEdit riServis
        {
            get
            {
                RepositoryItemGridLookUpEdit ri = GetCustomRI("Servis", false, "MTM", "RTW");
                return ri;
            }
        }

    }
}
